from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import psutil
import platform
import socket
import datetime
import json
from pathlib import Path

app = FastAPI(title="系统信息监控", description="实时显示系统资源使用情况")

def get_system_info():
    """获取系统信息"""
    # CPU信息
    cpu_percent = psutil.cpu_percent(interval=1)
    cpu_count = psutil.cpu_count()
    cpu_freq = psutil.cpu_freq()
    
    # 内存信息
    memory = psutil.virtual_memory()
    swap = psutil.swap_memory()
    
    # 磁盘信息
    disk_usage = psutil.disk_usage('/')
    
    # 网络信息
    network_io = psutil.net_io_counters()
    
    # 系统信息
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
    uptime = datetime.datetime.now() - boot_time
    
    # 进程信息
    processes = len(psutil.pids())
    
    return {
        "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "system": {
            "platform": platform.system(),
            "platform_release": platform.release(),
            "platform_version": platform.version(),
            "architecture": platform.machine(),
            "hostname": socket.gethostname(),
            "ip_address": socket.gethostbyname(socket.gethostname()),
            "boot_time": boot_time.strftime("%Y-%m-%d %H:%M:%S"),
            "uptime": str(uptime).split('.')[0],
            "processes": processes
        },
        "cpu": {
            "usage_percent": round(cpu_percent, 1),
            "count": cpu_count,
            "frequency": {
                "current": round(cpu_freq.current, 2) if cpu_freq else 0,
                "min": round(cpu_freq.min, 2) if cpu_freq else 0,
                "max": round(cpu_freq.max, 2) if cpu_freq else 0
            }
        },
        "memory": {
            "total": round(memory.total / (1024**3), 2),
            "available": round(memory.available / (1024**3), 2),
            "used": round(memory.used / (1024**3), 2),
            "percentage": round(memory.percent, 1),
            "swap_total": round(swap.total / (1024**3), 2),
            "swap_used": round(swap.used / (1024**3), 2),
            "swap_percentage": round(swap.percent, 1)
        },
        "disk": {
            "total": round(disk_usage.total / (1024**3), 2),
            "used": round(disk_usage.used / (1024**3), 2),
            "free": round(disk_usage.free / (1024**3), 2),
            "percentage": round((disk_usage.used / disk_usage.total) * 100, 1)
        },
        "network": {
            "bytes_sent": round(network_io.bytes_sent / (1024**2), 2),
            "bytes_recv": round(network_io.bytes_recv / (1024**2), 2),
            "packets_sent": network_io.packets_sent,
            "packets_recv": network_io.packets_recv
        }
    }

@app.get("/", response_class=HTMLResponse)
async def home():
    """主页面"""
    html_content = """
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>系统信息监控</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            body {
                font-family: 'Segoe UI', Arial, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                padding: 20px;
                color: #333;
            }
            
            .container {
                max-width: 1200px;
                margin: 0 auto;
            }
            
            .header {
                text-align: center;
                color: white;
                margin-bottom: 30px;
            }
            
            .header h1 {
                font-size: 2.5em;
                margin-bottom: 10px;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
            }
            
            .timestamp {
                background: rgba(255,255,255,0.2);
                padding: 10px 20px;
                border-radius: 20px;
                display: inline-block;
                backdrop-filter: blur(10px);
            }
            
            .grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
                gap: 20px;
                margin-bottom: 20px;
            }
            
            .card {
                background: rgba(255,255,255,0.95);
                border-radius: 15px;
                padding: 25px;
                box-shadow: 0 8px 32px rgba(0,0,0,0.1);
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255,255,255,0.2);
                transition: transform 0.3s ease;
            }
            
            .card:hover {
                transform: translateY(-5px);
            }
            
            .card h3 {
                color: #4a5568;
                margin-bottom: 15px;
                font-size: 1.3em;
                border-bottom: 2px solid #667eea;
                padding-bottom: 8px;
            }
            
            .info-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px 0;
                padding: 8px 0;
            }
            
            .info-label {
                font-weight: 600;
                color: #2d3748;
            }
            
            .info-value {
                color: #4a5568;
                font-family: 'Courier New', monospace;
            }
            
            .progress-bar {
                width: 100%;
                height: 20px;
                background: #e2e8f0;
                border-radius: 10px;
                overflow: hidden;
                margin: 5px 0;
            }
            
            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #667eea, #764ba2);
                border-radius: 10px;
                transition: width 0.3s ease;
                position: relative;
            }
            
            .progress-text {
                position: absolute;
                width: 100%;
                text-align: center;
                line-height: 20px;
                font-size: 12px;
                font-weight: bold;
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .refresh-btn {
                position: fixed;
                bottom: 30px;
                right: 30px;
                background: linear-gradient(45deg, #667eea, #764ba2);
                color: white;
                border: none;
                border-radius: 50px;
                padding: 15px 25px;
                font-size: 16px;
                cursor: pointer;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
                transition: all 0.3s ease;
            }
            
            .refresh-btn:hover {
                transform: scale(1.05);
                box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
            }
            
            .status-indicator {
                display: inline-block;
                width: 12px;
                height: 12px;
                border-radius: 50%;
                margin-right: 8px;
            }
            
            .status-good { background-color: #48bb78; }
            .status-warning { background-color: #ed8936; }
            .status-danger { background-color: #f56565; }
            
            @media (max-width: 768px) {
                .grid {
                    grid-template-columns: 1fr;
                }
                
                .header h1 {
                    font-size: 2em;
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🖥️ 系统信息监控</h1>
                <div class="timestamp" id="timestamp"></div>
            </div>
            
            <div class="grid" id="system-grid">
                <!-- 系统信息将在这里动态加载 -->
            </div>
        </div>
        
        <button class="refresh-btn" onclick="loadSystemInfo()">
            🔄 刷新数据
        </button>
        
        <script>
            async function loadSystemInfo() {
                try {
                    const response = await fetch('/api/system-info');
                    const data = await response.json();
                    renderSystemInfo(data);
                } catch (error) {
                    console.error('获取系统信息失败:', error);
                }
            }
            
            function getStatusClass(percentage) {
                if (percentage < 70) return 'status-good';
                if (percentage < 85) return 'status-warning';
                return 'status-danger';
            }
            
            function renderSystemInfo(data) {
                document.getElementById('timestamp').textContent = 
                    `最后更新: ${data.timestamp}`;
                
                const grid = document.getElementById('system-grid');
                grid.innerHTML = `
                    <div class="card">
                        <h3>🖥️ 系统信息</h3>
                        <div class="info-item">
                            <span class="info-label">操作系统:</span>
                            <span class="info-value">${data.system.platform} ${data.system.platform_release}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">架构:</span>
                            <span class="info-value">${data.system.architecture}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">主机名:</span>
                            <span class="info-value">${data.system.hostname}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">IP地址:</span>
                            <span class="info-value">${data.system.ip_address}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">运行时间:</span>
                            <span class="info-value">${data.system.uptime}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">进程数:</span>
                            <span class="info-value">${data.system.processes}</span>
                        </div>
                    </div>
                    
                    <div class="card">
                        <h3>💻 CPU信息</h3>
                        <div class="info-item">
                            <span class="info-label">
                                <span class="status-indicator ${getStatusClass(data.cpu.usage_percent)}"></span>
                                使用率:
                            </span>
                            <span class="info-value">${data.cpu.usage_percent}%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${data.cpu.usage_percent}%">
                                <div class="progress-text">${data.cpu.usage_percent}%</div>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">核心数:</span>
                            <span class="info-value">${data.cpu.count}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">当前频率:</span>
                            <span class="info-value">${data.cpu.frequency.current} MHz</span>
                        </div>
                    </div>
                    
                    <div class="card">
                        <h3>🧠 内存信息</h3>
                        <div class="info-item">
                            <span class="info-label">
                                <span class="status-indicator ${getStatusClass(data.memory.percentage)}"></span>
                                内存使用:
                            </span>
                            <span class="info-value">${data.memory.used}GB / ${data.memory.total}GB</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${data.memory.percentage}%">
                                <div class="progress-text">${data.memory.percentage}%</div>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">可用内存:</span>
                            <span class="info-value">${data.memory.available}GB</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <span class="status-indicator ${getStatusClass(data.memory.swap_percentage)}"></span>
                                交换空间:
                            </span>
                            <span class="info-value">${data.memory.swap_used}GB / ${data.memory.swap_total}GB</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${data.memory.swap_percentage}%">
                                <div class="progress-text">${data.memory.swap_percentage}%</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <h3>💾 磁盘信息</h3>
                        <div class="info-item">
                            <span class="info-label">
                                <span class="status-indicator ${getStatusClass(data.disk.percentage)}"></span>
                                磁盘使用:
                            </span>
                            <span class="info-value">${data.disk.used}GB / ${data.disk.total}GB</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${data.disk.percentage}%">
                                <div class="progress-text">${data.disk.percentage}%</div>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">可用空间:</span>
                            <span class="info-value">${data.disk.free}GB</span>
                        </div>
                    </div>
                    
                    <div class="card">
                        <h3>🌐 网络信息</h3>
                        <div class="info-item">
                            <span class="info-label">发送数据:</span>
                            <span class="info-value">${data.network.bytes_sent}MB</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">接收数据:</span>
                            <span class="info-value">${data.network.bytes_recv}MB</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">发送包数:</span>
                            <span class="info-value">${data.network.packets_sent.toLocaleString()}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">接收包数:</span>
                            <span class="info-value">${data.network.packets_recv.toLocaleString()}</span>
                        </div>
                    </div>
                `;
            }
            
            // 页面加载时获取系统信息
            loadSystemInfo();
            
            // 每30秒自动刷新
            setInterval(loadSystemInfo, 30000);
        </script>
    </body>
    </html>
    """
    return html_content

@app.get("/api/system-info")
async def get_system_info_api():
    """API接口：获取系统信息"""
    return get_system_info()

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "timestamp": datetime.datetime.now()}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)